/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.web.configure;

import com.aduib.boot.web.constants.AppConstants;
import com.aduib.boot.web.exception.DateFormatErrorException;
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * @description: DateTypeConverter
 * @author: zzh
 * @date: 2021/9/4 15:45
 */
public class DateTypeConverter implements Converter<String, Date> {

  Pattern datePatternCompile = Pattern.compile(AppConstants.DATE_PATTERN);

  Pattern timePatternCompile = Pattern.compile(AppConstants.TIME_PATTERN);

  Pattern dateTimePatternCompile = Pattern.compile(AppConstants.DATE_TIME_PATTERN);

  @Override
  public Date convert(String s) {
    SimpleDateFormat dateTimeFormat = new SimpleDateFormat(AppConstants.DATE_TIME_FORMAT);
    SimpleDateFormat dateFormat = new SimpleDateFormat(AppConstants.DATE_FORMAT);
    SimpleDateFormat timeFormat = new SimpleDateFormat(AppConstants.TIME_FORMAT);
    if (datePatternCompile.matcher(s).matches()){
      try {
        return dateFormat.parse(s);
      } catch (ParseException e) {
        throw new DateFormatErrorException(String.format("date %s format error",s));
      }
    }else if(timePatternCompile.matcher(s).matches()){
      try {
        return timeFormat.parse(s);
      } catch (ParseException e) {
        throw new DateFormatErrorException(String.format("date %s format error",s));
      }
    }else if (dateTimePatternCompile.matcher(s).matches()){
      try {
        return dateTimeFormat.parse(s);
      } catch (ParseException e) {
        throw new DateFormatErrorException(String.format("date %s format error",s));
      }
    }else{
      throw new DateFormatErrorException(String.format("date %s format error",s));
    }
  }
}
